
from .global_canvas import canvas
from .op_pixel import *
import numpy as np
import math



# 正规化颜色
green = np.array([0, 200, 0]) / 255
white = np.array([255, 255, 255]) / 255
black = np.array([0, 0, 0]) / 255
red = np.array([0, 0, 200]) / 255
blue = np.array([200, 0, 0]) / 255



def c255(c):
    return (c*255).astype(np.int8)
def norm(c_):
    return ((c_.astype(np.int)+256)&255)/256

# 颜色线性化，比gammar更本质
def linerlight(c):
    return np.power(c, 2)
def comeback(l):
    return np.power(l, 0.5)



def lineralpha(c, oc, a):
    return comeback(linerlight(c)*a + linerlight(oc)*(1-a))




#实数绘制部分


def finedraw_dot(x, y, c):
    right, x = math.modf(x)
    top, y = math.modf(y)
    x, y = int(x), int(y)
    left = 1 - right
    bottom = 1 - top
    oc1 = norm(canvas[y, x])
    oc2 = norm(canvas[y, x+1])
    oc3 = norm(canvas[y+1, x])
    oc4 = norm(canvas[y+1, x+1])
    canvas[y, x] = c255(lineralpha(c, oc1, left * bottom))
    canvas[y, x+1] = c255(lineralpha(c, oc2 , right * bottom))
    canvas[y+1, x] = c255(lineralpha(c, oc3 , left * top))
    canvas[y+1, x+1] = c255(lineralpha(c, oc4 , right * top))

def finedraw_line(x1, y1, x2, y2, c):
    _, x1 = math.modf(x1)
    _, y1 = math.modf(y1)
    _, x2 = math.modf(x2)
    _, y2 = math.modf(y2)
    x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)

    if x2 - x1 == 0:
        draw_vertical(x1, min(y1, y2), abs(y2-y1), c255(c))
        return

    #WUAADrawLine(img,start,end):
    if x1 > x2:
        x1, y1, x2, y2 = x2, y2, x1, y1
    k = float(y2 - y1) / (x2 - x1)
    if k < 1:
        y = y1
        for x in range(x1, x2):
            off = y - int(y)
            oc = norm(canvas[int(y) % 600, x % 800])
            canvas[int(y) % 600, x % 800] = c255(lineralpha(c, oc, (1-off)))
            oc = norm(canvas[(int(y)+1) % 600, x % 800])
            canvas[(int(y)+1)% 600, x % 800] = c255(lineralpha(c, oc, off))
            y += k
    else:
        k = float(x2 - x1)/(y2 - y1)
        x = x1
        for y in range(y1,y2):
            off = x - int(x)
            oc = norm(canvas[y % 600, int(x) % 800])
            canvas[y % 600, int(x) % 800] = c255(lineralpha(c, oc, (1-off)))
            oc = norm(canvas[y % 600, (int(x)+1) % 800])
            canvas[y % 600, (int(x)+1) % 800] = c255(lineralpha(c, oc, off))
            x += k






